package threadbase;

import java.security.*;

/**
 * java 线程安全
 *
 * @author xujian
 * Creation date 2024/4/9 22:57
 * @version 1.0
 */
public class JavaThreadSecurityDemo {

    public static void main(String[] args) {

        SafeRunnableImpl s = new SafeRunnableImpl();
        Thread t = new Thread(s,"cess");
        t.start();
        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static class SafeRunnableImpl extends SafeRunnable {
        @Override
        protected Void execute() {
            System.exit(0);
            return null;
        }
    }



    private abstract static class SafeRunnable implements Runnable{
        /*子类继承*/
        protected abstract Void execute();
        @Override
        public void run() {
            /*开启安全管理器*/
            SecurityManager securityManager = new SecurityManager();
            System.setSecurityManager(securityManager);

            /*代码签名*/
            CodeSource codeSource = new CodeSource(this.getClass().getResource("/"),(CodeSigner[]) null);

            /*权限*/
            RuntimePermission runtimePermission = new RuntimePermission("exitVM");
            Permissions permission = new Permissions();
            permission.add(runtimePermission);

            /*保护域*/
            ProtectionDomain protectionDomain = new ProtectionDomain(codeSource,permission);

            /*权限上下文*/
            AccessControlContext controlContext = new AccessControlContext(new ProtectionDomain[]{protectionDomain});

            AccessController.doPrivileged((PrivilegedAction<Void>) this::execute,controlContext);
        }
    }
}


